package expertise.titan.environment.impl;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.thinkaurelius.titan.core.TitanKey;
import com.thinkaurelius.titan.core.TitanLabel;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;

import expertise.titan.datasource.TitanDataSource;
import expertise.titan.environment.ExpertiseTitanEnvironmentConfigurer;

@Component
public class ExpertiseTitanEnvironmentConfigurerImpl implements
		ExpertiseTitanEnvironmentConfigurer, InitializingBean {

	@Resource
	private TitanDataSource dataSource;

	private static final Logger log = Logger.getLogger(ExpertiseTitanEnvironmentConfigurer.class);

	public TitanKey vertexNameKey;

	public TitanKey vertexTypeKey;

	public TitanLabel edgeTypeLabel;

	@Override
	public void afterPropertiesSet() throws Exception {
		log.info("Configuring Titan graph layer");
		configureVertexIndicies();
		configureEdgeIndicies();
	}

	private void configureEdgeIndicies() {
		log.debug("Configuring Edge Indicies");
		final Set<String> labels = dataSource.graph().getIndexedKeys(Edge.class);
		if (!labels.contains("edgeType")) {
			edgeTypeLabel = dataSource.graph().makeLabel("edgeType").directed().oneToMany().make();
		} else {
			edgeTypeLabel = (TitanLabel) dataSource.graph().getType("edgeType");
		}
	}

	private void configureVertexIndicies() {
		log.debug("Configuring Vertex Indicies");
		final Set<String> keys = dataSource.graph().getIndexedKeys(Vertex.class);
		if (!keys.contains("name")) {
			vertexNameKey = dataSource.graph().makeKey("name").dataType(String.class)
					.indexed(Vertex.class).unique().make();
		} else {
			vertexNameKey = (TitanKey) dataSource.graph().getType("name");
		}
		if (!keys.contains("type")) {
			vertexTypeKey = dataSource.graph().makeKey("type").dataType(String.class)
					.indexed(Vertex.class).make();
		} else {
			vertexTypeKey = (TitanKey) dataSource.graph().getType("type");
		}
		dataSource.graph().commit();
	}

	@Override
	public TitanKey vertexNameKey() {
		return vertexNameKey;
	}

	@Override
	public TitanKey vertexTypeKey() {
		return vertexTypeKey;
	}

}
